<?php

    define('ROOT_PATH', dirname(dirname(dirname(__FILE__))) . '/');
    
    require_once ROOT_PATH . 'dynamic/libs/common.fn.php';
    require_once ROOT_PATH . 'dynamic/libs/class.rudonSqlite.php';

    $protocol = (check_is_https())? 'https://': 'http://';
    define('LINK_ROOT', $protocol. $_SERVER['HTTP_HOST'].'/');
    



    class urls {

        /* SQLite数据库文件地址 */
        public $db_file_path = ROOT_PATH . 'dynamic/db/db.db';

        /* SQLite数据库操作类 */
        public $db;


        // 构造函数
        public function __construct () {
            
            if (!file_exists($this->db_file_path)) {
                alert('数据库不存在');
            }
            $this->db = new rudonSqlite($this->db_file_path);
        }

        // 显示模版
        public function view ($name, $replaces_array = array()) {
            $fullpath = ROOT_PATH . 'dynamic/tpls/' . $name . '.html';
            if (!file_exists($fullpath)) {
                alert('模版不存在');
            }
            $c = file_get_contents($fullpath);

            // 替换
            if (is_array($replaces_array) && count($replaces_array)) {
                foreach ($replaces_array as $from => $to) {
                    $c = str_replace($from, $to, $c);
                }
            }

            echo $c;
            die();
        }

        // 显示首页
        public function action () {

            // 读数据
            $sql = "select * from urls order by id desc limit 200";
            $dbres = $this->db->query($sql);

            $html = '';
            foreach ($dbres as $one) {
                $html .= '<tr><td>'.$one['id'].'</td><td>'.date('m-d H:i', $one['create_time']).'</td><td><a href="'.LINK_ROOT . $one['url_short'].'" target="_blank">'.$one['url_short'].'</a></td><td><div class="">'.substr($one['url_long'], 0, 40).'...</div></td></tr>';
            }

            // 展现模版
            $replaces = array(
                '<!--{{$html}}-->' => $html
            );
            $this->view('history', $replaces);
            
        }



    } // CLASS ENDING

    // 启动
    $app = new urls();
    $app->action();